package com.mxnet.chongjin.supoman.activity;

import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.bean.RepairRecord;
import com.mxnet.chongjin.supoman.config.Api;
import com.mxnet.chongjin.supoman.utils.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class RepairOrderApplyingActivity extends AppCompatActivity implements View.OnClickListener {
    private Context mContext;
    private LinearLayout mLinearLayout, mLayout;
    private RepairRecord mRepairRecord;
    private Button mButton;
    private TextView mTvOrderNum, mTvXulieNum, mTvMachineInfo, mTvPartnerName, mTvPartnerTel, mTvPartnerAddr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_repair_order_applying);
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        getWindow().setStatusBarColor(Color.TRANSPARENT);
        mContext = RepairOrderApplyingActivity.this;
        Bundle bundle = getIntent().getExtras();
        mRepairRecord = bundle.getParcelable("record");

        initData();
        initView();
    }

    public void initView() {
        mLinearLayout = findViewById(R.id.ll_repair_order_applying);
        mLinearLayout.setOnClickListener(this);

        mLayout = findViewById(R.id.ll_repair_order_applying_2);
        for (int i = 0; i < mRepairRecord.getResourceIdList().size(); i++) {
            ImageView imageView = new ImageView(mContext);
            Glide.with(mContext).load(Api.URL_HEADER + Api.GET_IMAGE + mRepairRecord.getResourceIdList().get(i)).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(imageView);
            mLayout.addView(imageView);
        }

        mButton = findViewById(R.id.btn_repair_order_applying);
        mButton.setOnClickListener(this);

        mTvOrderNum = findViewById(R.id.tv_repair_order_applying_order_num);
        mTvOrderNum.setText(getResources().getString(R.string.repair_num) + mRepairRecord.getDeclarationNo());

        mTvXulieNum = findViewById(R.id.tv_repair_order_applying_xulie_num);
        mTvXulieNum.setText(getResources().getString(R.string.serial_number) + mRepairRecord.getProjectNo());

        mTvMachineInfo = findViewById(R.id.tv_repair_order_applying_machine_info);
        mTvMachineInfo.setText(mRepairRecord.getDeclarationMemo());

        mTvPartnerName = findViewById(R.id.tv_repair_order_applying_partner_name);
        mTvPartnerName.setText(getResources().getString(R.string.partner_name) + mRepairRecord.getCustomerName());

        mTvPartnerTel = findViewById(R.id.tv_repair_order_applying_partner_tel);
        mTvPartnerTel.setText(getResources().getString(R.string.contact) + mRepairRecord.getCustomerMobile());

        mTvPartnerAddr = findViewById(R.id.tv_repair_order_applying_partner_addr);
        mTvPartnerAddr.setText(getResources().getString(R.string.contact_addr) + mRepairRecord.getCountry() + mRepairRecord.getCity() + mRepairRecord.getDistirct() + mRepairRecord.getDetailAddress());

    }

    public void initData() {
        OkHttpUtils.get()
                .url(Api.URL_HEADER + Api.REPAIR_DETAIL)
                .addParams("id", mRepairRecord.getId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (!TextUtils.isEmpty(response)) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                boolean isSuccess = jsonObject.optBoolean("success");
                                if (isSuccess) {
                                    JSONArray data = jsonObject.optJSONArray("data");
                                    if (data != null) {
                                        for (int i = 0; i < data.length(); i++) {
                                            RepairRecord record = new RepairRecord();
                                            JSONObject object = data.optJSONObject(i);
                                            record.setCountry(object.optString("country"));
                                            record.setZipCode(object.optString("zipCode"));
                                            record.setRobotNo(object.optString("robotNo"));
                                            record.setSalerName(object.optString("salerName"));
                                            record.setDeclarationMemo(object.optString("declarationMemo"));
                                            record.setCity(object.optString("city"));
                                            record.setDeclarationNo(object.optString("declarationNo"));
                                            record.setCustomerName(object.optString("customerName"));
                                            record.setRobotImgUrl(object.optString("robotImgUrl"));
                                            RepairRecord.ImgResourceBean imgResourceBean = new RepairRecord.ImgResourceBean();
                                            JSONObject object1 = object.optJSONObject("imgResource");
                                            imgResourceBean.setCreateTime(object1.optLong("createTime"));
                                            imgResourceBean.setFileType(object1.optString("fileType"));
                                            imgResourceBean.setId(object1.optString("id"));
                                            imgResourceBean.setMd5(object1.optString("md5"));
                                            imgResourceBean.setName(object1.optString("name"));
                                            imgResourceBean.setSize(object1.optString("size"));
                                            imgResourceBean.setType(object1.optString("type"));
                                            imgResourceBean.setUrl(object1.optString("url"));
                                            imgResourceBean.setUserId(object1.optString("userId"));
                                            record.setImgResource(imgResourceBean);
                                            record.setProjectNo(object.optString("projectNo"));
                                            record.setDistirct(object.optString("distirct"));
                                            record.setCreateTime(object.optLong("createTime"));
                                            record.setSalerNo(object.optString("salerNo"));
                                            record.setDetailAddress(object.optString("detailAddress"));
                                            record.setDeclarationStatus(object.optString("declarationStatus"));
                                            record.setId(object.optString("id"));
                                            record.setCustomerMobile(object.optString("customerMobile"));
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_repair_order_applying:
                new Thread() {
                    public void run() {
                        try {
                            Instrumentation inst = new Instrumentation();
                            inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
                break;
            case R.id.btn_repair_order_applying:
                //                Map<String, String> data = new HashMap<String, String>();
                //                data.put("declarationNo", mRepairRecord.getDeclarationNo());
                //                data.put("maintenanceMemo","维修已受理，等待上门");
                OkHttpUtils.get()
                        .url(Api.URL_HEADER + Api.ACCEPT_MAINTENANCE_LIST)
                        .addParams("declarationNo", mRepairRecord.getDeclarationNo())
                        .addParams("maintenanceMemo", "维修已受理，等待上门")
                        .build()
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean isSuccess = jsonObject.optBoolean("success");
                                        if (isSuccess) {
                                            ToastUtils.showToast(mContext, "受理成功！");
                                            Intent intent = new Intent();
                                            intent.setClass(mContext, RepairOrderActivity.class);
                                            startActivityForResult(intent, 800);
                                            restartApplication();
                                        } else {
                                            ToastUtils.showToast(mContext, jsonObject.optString("msg"));
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                break;
        }
    }

    private void restartApplication() {
        final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}
